package sk.fei.vrml.objects;

import java.nio.ByteBuffer;
import java.nio.IntBuffer;

import javax.media.opengl.GL;
import sk.fei.vrml.main.Constants;

public class PixelTextureObject  extends TextureObject{
	private int imageWidth,imageHeight,colorBytes;
	private boolean repeatS,repeatT;
	private byte[] pixels;
	private int[] textureId;
	private boolean converted = false;
	
	
	public PixelTextureObject(){
		super();
		this.textureType = Constants.PixelTexture;
		this.imageWidth = 0;
		this.imageHeight = 0;
		this.colorBytes = 3;
		this.repeatS = true;
		this.repeatT = true;
		this.pixels = null;
		this.textureId = new int[1];
	}
	
	public PixelTextureObject(int width, int height, int depth, boolean s, boolean t,byte[] pixel){
		super();
		this.textureType = Constants.PixelTexture;
		this.imageWidth = width;
		this.imageHeight = height;
		this.colorBytes = depth;
		this.repeatS = s;
		this.repeatT = t;
		this.pixels = pixel;
		this.textureId = new int[1];
	}
	
	public void prepareTexture(GL gl){
		if (!converted){
			ByteBuffer directBuf = ByteBuffer.allocateDirect((pixels.length+2)*Byte.SIZE);
			directBuf.put((byte)0).put((byte)0); // offset napevno pridany koli tomu ze to chce jogl 2.0
			for (int i =0; i<pixels.length; i++){
				directBuf.put((byte)(pixels[i] & 0xff));
			}
			directBuf.flip();
			gl.glEnable(GL.GL_TEXTURE_2D);
			gl.glGenTextures(1, IntBuffer.wrap(textureId));
			gl.glBindTexture(GL.GL_TEXTURE_2D, textureId[0]);	
			int format = getPixelFormat(colorBytes);
			if (format == 0) return;
			gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, format, imageWidth, imageHeight, 0, format, GL.GL_BYTE, directBuf);	
			converted = true;
			gl.glDisable(GL.GL_TEXTURE_2D);
		}
	}	
	
	public void bindTexture(GL gl){
		gl.glEnable(GL.GL_TEXTURE_2D);
		gl.glBindTexture(GL.GL_TEXTURE_2D, textureId[0]);
	}

	public int getPixelFormat(int num){
		if (num == 1) return GL.GL_LUMINANCE;
		else if (num == 2) return GL.GL_LUMINANCE_ALPHA;
		else if (num == 3) return GL.GL_RGB;
		else if (num == 4) return GL.GL_RGBA;
		else return 0;
	}
	
	public int getTextureId(){
		return textureId[0];
	}
	
	public int getTextureWidth(){
		return imageWidth;
	}
	
	public int getTextureHeight(){
		return imageHeight;
	}
	
	public int getTextureFormat(){
		return colorBytes;
	}
	
	public byte[] getTextureBytes(){
		return pixels;
	}
	
	public boolean isRepeatS() {
		return repeatS;
	}

	public boolean isRepeatT() {
		return repeatT;
	}

}
